#include "CameraBase.h"

static int CameraBaseObjCount = -1;

CameraBase::CameraBase()
{
    CameraBaseObjCount++;
    handle = CameraBaseObjCount;
}

void CameraBase::YV12_RGB24(unsigned char* pYV12, unsigned char* pRGB24, int width, int height)
{
    const long yLen = long(height * width);
    const int halfWidth = (width >> 1);

    unsigned char* yData = pYV12;
    unsigned char* vData = &yData[yLen];
    unsigned char* uData = &vData[yLen >> 2];

    int rgb[3];
    int i, j, m, n, x, y, widthDepth;
    m = -width;
    n = -halfWidth;
    widthDepth = width + width + width;

    for (y = 0; y < height; y++)
    {
        int rByte, cByte;
        rByte = y * widthDepth;
        m += width;
        if (!(y % 2))
            n += halfWidth;
        for (x = 0; x < width; x++)
        {
            cByte = x + x + x;
            i = m + x;
            j = n + (x >> 1);
            rgb[2] = int(yData[i] + 1.370705 * (vData[j] - 128));
            rgb[1] = int(yData[i] - 0.698001 * (uData[j] - 128) - 0.703125 * (vData[j] - 128));
            rgb[0] = int(yData[i] + 1.732446 * (uData[j] - 128));

            for (j = 0; j < 3; ++j)
            {
                if (rgb[j] >= 0 && rgb[j] <= 255)
                    pRGB24[rByte + cByte + j] = rgb[j];
                else
                    pRGB24[rByte + cByte + j] = (rgb[j] < 0) ? 0 : 255;
            }
        }
    }
}
